//
//  Syncronize.m
//  InterventixApp
//
//  Created by Diego on 29/01/13.
//  Copyright (c) 2013 __MyCompanyName__. All rights reserved.
//

#import "Syncronize.h"
#import "SBJson.h"
#import "Define.h"
#import "CryptoCR2.h"
#import "Intervento.h"
#import "DateUtil.h"
#import "Buffer.h"

@implementation Syncronize

/*
// CLIENTI
+(void) updateClients:(NSArray *) clients from:(Utente *) u{
    if([clients count] > 0){
        NSString *stringCR2 = (NSString *) [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@__%@",SAVE_CLIENTS,u.idUtente]];
        NSMutableArray *revs;
        if(stringCR2!=nil){
            NSString *dec = [CryptoCR2 decrypt:stringCR2];
            revs = [dec JSONValue];
        }else {
            revs = [[NSMutableArray alloc] initWithCapacity:0];
        }
        
        for(NSDictionary *clienteNew in clients){
            NSString *idclienteNew = (NSString *)[clienteNew objectForKey:@"idcliente"];
            NSDictionary *clienteOld = [Syncronize findClient:idclienteNew on:revs];
            if(clienteOld != nil){
                [revs removeObject:clienteOld];
            }
            [revs addObject:clienteNew];
            NSLog(@"Update Client %@",idclienteNew);
        }
        //NSLog(@"%@",(NSString *)[CryptoCR2 encrypt:[revs JSONRepresentation]]);
        
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:[NSString stringWithFormat:@"%@__%@",SAVE_CLIENTS,u.idUtente]];
        [[NSUserDefaults standardUserDefaults] setObject:(NSString *)[CryptoCR2 encrypt:[revs JSONRepresentation]] forKey:[NSString stringWithFormat:@"%@__%@",SAVE_CLIENTS,u.idUtente]];
    }
}
+(void) deleteClients:(NSArray *) clients from:(Utente *) u{
    if([clients count] > 0){
        NSString *stringCR2 = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@__%@",SAVE_CLIENTS,u.idUtente]];
        NSMutableArray *revs;
        if(stringCR2!=nil){
            NSString *dec = [CryptoCR2 decrypt:stringCR2];
            revs = [dec JSONValue];
        }else {
            revs = [[NSMutableArray alloc] initWithCapacity:0];
        }
        for(NSString *idclient in clients){
            NSLog(@"Delete Client %@",idclient);
            NSDictionary *clienteOld = [Syncronize findClient:idclient on:revs];
            [revs removeObject:clienteOld];
        }
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:SAVE_CLIENTS];
        [[NSUserDefaults standardUserDefaults] setObject:(NSString *)[CryptoCR2 encrypt:[revs JSONRepresentation]] forKey:[NSString stringWithFormat:@"%@__%@",SAVE_CLIENTS,u.idUtente]];
    }
}
+(NSDictionary *) findClient:(NSString *) idclient on:(NSMutableArray *) clients{
    for(NSDictionary *c in clients){
        NSString *idcliente = (NSString *)[c objectForKey:@"idcliente"];
        if([idcliente intValue] == [idclient intValue]){
            return c;
        }
    }
    return nil;
}
+(NSArray *) findClientsLike:(NSString *) nominativo{
    if([nominativo isEqualToString:@""]){
        return [self findClientsLastUsed];
    }else if(nominativo == nil){
        return [self findClientsLastUsed];
    }
    else if([nominativo length] == 0){
        return [self findClientsLastUsed];
    }
    else{
        NSString *stringCR2 = [[NSUserDefaults standardUserDefaults] objectForKey:SAVE_CLIENTS];
        NSMutableArray *revs;
        if(stringCR2!=nil){
            NSString *dec = [CryptoCR2 decrypt:stringCR2];
            revs = [dec JSONValue];
        }else {
            revs = [[NSMutableArray alloc] initWithCapacity:0];
        }
        
        NSMutableArray *arr = [[NSMutableArray alloc] initWithCapacity:0];
        
        for(NSDictionary *c in revs){
            if([[c objectForKey:@"nominativo"] rangeOfString:nominativo options:NSCaseInsensitiveSearch].location != NSNotFound){
                [arr addObject:c];
            }
        }
        
        return arr;
    }
}
+(NSArray *) findClientsLastUsed{
    
    NSString *last = [[NSUserDefaults standardUserDefaults] objectForKey:LAST_USED_CLIENT];
    
    if(last != nil){
        NSMutableArray *revs;
        NSString *dec = [CryptoCR2 decrypt:last];
        revs = [dec JSONValue];
        return revs;
    }else{
        NSString *stringCR2 = [[NSUserDefaults standardUserDefaults] objectForKey:SAVE_CLIENTS];
        NSMutableArray *revs;
        if(stringCR2!=nil){
            NSString *dec = [CryptoCR2 decrypt:stringCR2];
            revs = [dec JSONValue];
        }else {
            revs = [[NSMutableArray alloc] initWithCapacity:0];
        }
        
        NSMutableArray *arr = [[NSMutableArray alloc] initWithCapacity:0];
        
        int x=0;
        for(NSDictionary *c in revs){
            if(x<10){
                [arr addObject:c];
                x++;
            }
            
        }
        return arr;
        
    }
}

+(NSMutableArray *) getClients:(Utente *) u{
    NSString *stringCR2 = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@__%@",SAVE_CLIENTS,u.idUtente]];
    NSMutableArray *revs;
    if(stringCR2!=nil){
        NSString *dec = [CryptoCR2 decrypt:stringCR2];
        revs = [dec JSONValue];
    }else {
        revs = [[NSMutableArray alloc] initWithCapacity:0];
    }
    
    NSMutableArray *arrInt = [[NSMutableArray alloc] initWithCapacity:0];
    
    for(NSDictionary *c in revs){
        Cliente *i = [[Cliente alloc] init];
        [i readFromDictionary:c];
        [arrInt addObject:i];
    }
    
    return arrInt;
}


// INTERVENTI
+(void) updateIntervents:(NSArray *) intervents from:(Utente *) u{
    if([intervents count] > 0){
        NSString *stringCR2 = (NSString *) [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@__%@",SAVE_INTERVENTS,u.idUtente]];
        NSMutableArray *revs;
        if(stringCR2!=nil){
            NSString *dec = [CryptoCR2 decrypt:stringCR2];
            revs = [dec JSONValue];
        }else {
            revs = [[NSMutableArray alloc] initWithCapacity:0];
        }
        
        for(NSDictionary *interv in intervents){
            NSString *idinterv = (NSString *)[interv objectForKey:@"idintervento"];
            NSDictionary *intervOld = [Syncronize findIntervent:idinterv on:revs];
            if(intervOld != nil){
                [revs removeObject:intervOld];
            }
            [revs addObject:interv];
            NSLog(@"Update Intervents %@",idinterv);
        }        
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:[NSString stringWithFormat:@"%@__%@",SAVE_INTERVENTS,u.idUtente]];
        [[NSUserDefaults standardUserDefaults] setObject:(NSString *)[CryptoCR2 encrypt:[revs JSONRepresentation]] forKey:[NSString stringWithFormat:@"%@__%@",SAVE_INTERVENTS,u.idUtente]];
    }
}
+(void) deleteIntervents:(NSArray *) intervents from:(Utente *) u{
    if([intervents count] > 0){
        NSString *stringCR2 = (NSString *) [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@__%@",SAVE_INTERVENTS,u.idUtente]];
        NSMutableArray *revs;
        if(stringCR2!=nil){
            NSString *dec = [CryptoCR2 decrypt:stringCR2];
            revs = [dec JSONValue];
        }else {
            revs = [[NSMutableArray alloc] initWithCapacity:0];
        }
        
        for(NSString *interv in intervents){
            NSDictionary *intervOld = [Syncronize findIntervent:interv on:revs];
            [revs removeObject:intervOld];
            NSLog(@"Remove Intervents %@",interv);
        }
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:[NSString stringWithFormat:@"%@__%@",SAVE_INTERVENTS,u.idUtente]];
        [[NSUserDefaults standardUserDefaults] setObject:(NSString *)[CryptoCR2 encrypt:[revs JSONRepresentation]] forKey:[NSString stringWithFormat:@"%@__%@",SAVE_INTERVENTS,u.idUtente]];
    }
}
+(void) compareIntervents:(NSArray *) intervents from:(Utente *) u{
    if([intervents count] > 0){
        NSString *stringCR2 = (NSString *) [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@__%@",SAVE_INTERVENTS,u.idUtente]];
        NSMutableArray *revs;
        if(stringCR2!=nil){
            NSString *dec = [CryptoCR2 decrypt:stringCR2];
            revs = [dec JSONValue];
        }else {
            revs = [[NSMutableArray alloc] initWithCapacity:0];
        }
        NSMutableArray *revs2 = [[NSMutableArray alloc] initWithCapacity:0];
        NSMutableArray *buf = [Buffer getNewIntervents:u];
        
        for(NSString *interID in intervents){
            NSDictionary *intervOld = [Syncronize findIntervent:interID on:revs];
            if(intervOld!=nil){
                [revs2 addObject:intervOld];
            }else{
                Intervento *inter = [Buffer findIntervent:interID from:u];
                if(inter != nil){
                    [buf addObject:inter];
                }
                else{
                    //L'intervento NON esiste sia nel Syncro sia nel Buffer
                    //quindi significa che va richiesto di nuovo
                    //anche se non si dovrebbe mai verificare.
                    // *
                    // SOLUTIONE:
                     Possibile resettare il contatore di revisione e rilanciare la sincronizzazione da rev 0
                    ///
                }
            }
        }
        [Buffer save:buf from:u];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:[NSString stringWithFormat:@"%@__%@",SAVE_INTERVENTS,u.idUtente]];
        [[NSUserDefaults standardUserDefaults] setObject:(NSString *)[CryptoCR2 encrypt:[revs2 JSONRepresentation]] forKey:[NSString stringWithFormat:@"%@__%@",SAVE_INTERVENTS,u.idUtente]];
    }
}
+(void) deleteIntervent:(NSString *) idintervent from:(Utente *) u{
        NSString *stringCR2 = (NSString *) [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@__%@",SAVE_INTERVENTS,u.idUtente]];
        NSMutableArray *revs;
        if(stringCR2!=nil){
            NSString *dec = [CryptoCR2 decrypt:stringCR2];
            revs = [dec JSONValue];
        }else {
            revs = [[NSMutableArray alloc] initWithCapacity:0];
        }
        
            NSDictionary *intervOld = [Syncronize findIntervent:idintervent on:revs];
            [revs removeObject:intervOld];
            NSLog(@"Remove Intervents %@",idintervent);
        
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:[NSString stringWithFormat:@"%@__%@",SAVE_INTERVENTS,u.idUtente]];
        [[NSUserDefaults standardUserDefaults] setObject:(NSString *)[CryptoCR2 encrypt:[revs JSONRepresentation]] forKey:[NSString stringWithFormat:@"%@__%@",SAVE_INTERVENTS,u.idUtente]];
    
}

+(NSDictionary *) findIntervent:(NSString *) idintervent on:(NSMutableArray *) intervents{
    for(NSDictionary *i in intervents){
        NSString *idintervento = (NSString *)[i objectForKey:@"idintervento"];
        if([idintervento intValue] == [idintervent intValue]){
            return i;
        }
    }
    return nil;
}
+(NSMutableArray *) getIntervents:(Utente *) u{
    NSString *stringCR2 = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@__%@",SAVE_INTERVENTS,u.idUtente]];
    NSMutableArray *revs;
    if(stringCR2!=nil){
        NSString *dec = [CryptoCR2 decrypt:stringCR2];
        revs = [dec JSONValue];
    }else {
        revs = [[NSMutableArray alloc] initWithCapacity:0];
    }
    
    NSMutableArray *arrInt = [[NSMutableArray alloc] initWithCapacity:[revs count]];
    
    for(NSDictionary *c in revs){
        Intervento *i = [[Intervento alloc] init];
        [i readFromDictionary:c];
        [arrInt addObject:i];
    }
    
    
    
    NSMutableArray *arr = [[NSMutableArray alloc] initWithCapacity:[revs count]];
    
    NSString *order = [[NSUserDefaults standardUserDefaults]objectForKey:INTERVENTS_ORDER_BY_DATA];
    
    if(order != nil){
        if([order isEqualToString:@"ASC"]){
            //Order data asc
            while([arrInt count]>0){
                Intervento *i = [self popOldIntervents:arrInt];
                [arr addObject:i];
            }
        }
        
        if([order isEqualToString:@"DESC"]){
            //Order data DESC
            while([arrInt count]>0){
                Intervento *i = [self popNewIntervents:arrInt];
                [arr addObject:i];
            }
        }
    }else{
        //Order data asc
        while([arrInt count]>0){
            Intervento *i = [self popOldIntervents:arrInt];
            [arr addObject:i];
        }
    }
    
    return arr;
}

+(Intervento *) popOldIntervents:(NSMutableArray *) intervs{
    long long min = LONG_LONG_MAX;
    Intervento *s;
    for(Intervento *j in intervs){
        long long d = [DateUtil NSDateToLong:j.dataora];
        if(d < min){
            min = d;
            s = j;
        }
    }
    [intervs removeObject:s];
    return s;
}
+(Intervento *) popNewIntervents:(NSMutableArray *) intervs{
    long long max = 0;
    Intervento *s;
    for(Intervento *j in intervs){
        long long d = [DateUtil NSDateToLong:j.dataora];
        if(d > max){
            max = d;
            s = j;
        }
    }
    [intervs removeObject:s];
    return s;
}

// UTENTI
+(void) updateUsers:(NSArray *) users from:(Utente *) u{
    if([users count] > 0){
        NSString *stringCR2 = (NSString *) [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@__%@",SAVE_USERS,u.idUtente]];
        NSMutableArray *revs;
        if(stringCR2!=nil){
            NSString *dec = [CryptoCR2 decrypt:stringCR2];
            revs = [dec JSONValue];
        }else {
            revs = [[NSMutableArray alloc] initWithCapacity:0];
        }
        
        for(NSDictionary *user in users){
            NSString *iduser = (NSString *)[user objectForKey:@"idutente"];
            NSDictionary *userOld = [Syncronize findUser:iduser on:revs];
            if(userOld != nil){
                [revs removeObject:userOld];
            }
            [revs addObject:user];
            NSLog(@"Update user %@",iduser);
        }
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:[NSString stringWithFormat:@"%@__%@",SAVE_USERS,u.idUtente]];
        [[NSUserDefaults standardUserDefaults] setObject:(NSString *)[CryptoCR2 encrypt:[revs JSONRepresentation]] forKey:[NSString stringWithFormat:@"%@__%@",SAVE_USERS,u.idUtente]];
    }
}
+(void) deleteUsers:(NSArray *) users from:(Utente *) u{
    if([users count] > 0){
        NSString *stringCR2 = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@__%@",SAVE_USERS,u.idUtente]];
        NSMutableArray *revs;
        if(stringCR2!=nil){
            NSString *dec = [CryptoCR2 decrypt:stringCR2];
            revs = [dec JSONValue];
        }else {
            revs = [[NSMutableArray alloc] initWithCapacity:0];
        }
        for(NSString *iduser in users){
            NSLog(@"Delete user %@",iduser);
            NSDictionary *userOld = [Syncronize findUser:iduser on:revs];
            [revs removeObject:userOld];
        }
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:SAVE_USERS];
        [[NSUserDefaults standardUserDefaults] setObject:(NSString *)[CryptoCR2 encrypt:[revs JSONRepresentation]] forKey:[NSString stringWithFormat:@"%@__%@",SAVE_USERS,u.idUtente]];
    }
}
+(NSMutableArray *) getusers:(Utente *) u{
    NSString *stringCR2 = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@__%@",SAVE_USERS,u.idUtente]];
    NSMutableArray *revs;
    if(stringCR2!=nil){
        NSString *dec = [CryptoCR2 decrypt:stringCR2];
        revs = [dec JSONValue];
    }else {
        revs = [[NSMutableArray alloc] initWithCapacity:0];
    }
    
    NSMutableArray *arrInt = [[NSMutableArray alloc] initWithCapacity:0];
    
    for(NSDictionary *c in revs){
        Utente *i = [[Utente alloc] init];
        [i readFromDictionary:c];
        [arrInt addObject:i];
    }
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"cognome" ascending:YES];
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    
    NSArray *arr = [arrInt sortedArrayUsingDescriptors:sortDescriptors];
    NSMutableArray *marr = [[NSMutableArray alloc] initWithCapacity:arr.count];
    for(Utente *i in arr){
        [marr addObject:i];
    }
    return marr;
}

+(NSDictionary *) findUser:(NSString *) iduser on:(NSMutableArray *) users{
    for(NSDictionary *i in users){
        NSString *iduser_ = (NSString *)[i objectForKey:@"idintervento"];
        if([iduser_ intValue] == [iduser intValue]){
            return i;
        }
    }
    return nil;
}
+(NSDictionary *) findUser:(NSString *) iduser from:(Utente *) u{
    return [self findUser:iduser on:[self getusers:u]];
}
+(void) toString{
    NSString *stringCR2 = [[NSUserDefaults standardUserDefaults] objectForKey:SAVE_CLIENTS];
    NSMutableArray *revs;
    if(stringCR2!=nil){
        NSString *dec = [CryptoCR2 decrypt:stringCR2];
        revs = [dec JSONValue];
    }else {
        revs = [[NSMutableArray alloc] initWithCapacity:0];
    }
    NSLog(@"----------------------------------------------------");
    for(NSDictionary *c in revs){
        NSString *idcliente = (NSString *)[c objectForKey:@"idcliente"];
        NSString *nominativo = (NSString *)[c objectForKey:@"nominativo"];
        NSString *citta = (NSString *)[c objectForKey:@"citta"];
        NSLog(@"idcliente:%@ - nominativo:%@ - città:%@",idcliente,nominativo,citta);
    }
    
    //NSString *stringCR2_inter = [[NSUserDefaults standardUserDefaults] objectForKey:SAVE_INTERVENTS];
    //NSLog(@"INTERVENTS: %@",[CryptoCR2 decrypt:stringCR2_inter]);
}


+(Utente *) getUserLog{
    NSString *stringCR2 = (NSString *) [[NSUserDefaults standardUserDefaults] objectForKey:SAVE_USER];
    if(stringCR2 != nil){
        @try {
            NSString *dec = [CryptoCR2 decrypt:stringCR2];
            Utente *u =[Utente createFromDictionary:[dec JSONValue]];
            return u;
        }
        @catch (NSException *exception) {return nil;}
        @finally {}
    }
}
*/
    
    
@end
